package com.su.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.su.entity.Code;
import com.su.exception.GuiliException;
import com.su.utils.ModBusCommand;
import com.su.vo.R;
import com.su.entity.Study;
import com.su.entity.instruname;
import com.su.service.StudyService;
import com.su.service.instrunameService;
import com.su.vo.InnameVo;
import com.su.vo.StudyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/api/eduservice/study")
public class StudyController {

    @Autowired
    private StudyService studyService;

    @Autowired
    private ModBusCommand modBusCommand;

    @Autowired
    private instrunameService instrunameService;

    //使result为内存可见性
    private volatile boolean result;

//    @Autowired
//    private ClientService clientService;

    /**
     * 接受自学习上传的红外码解析并入库
     *
     * @param study
     * @return
     * @throws IOException
     */
    @RequestMapping("study")
    public R study(@RequestBody Study study) throws IOException {

        Study study1 = new Study();

        BeanUtils.copyProperties(study, study1);

        instruname serviceOne = instrunameService.getOne(new QueryWrapper<instruname>().eq("controllerid", study.getControllerid()));

        study1.setInstructionname(serviceOne.getName());

        study1.setInstructioncode(study.getAdresscode() + Code.getResultcode());

        study1.setStatus(String.valueOf(3));

        System.err.println("===========>" + study1);


        String code;

        try {
            code = studyService.sendinstruction(study1);
        } catch (ConnectException e) {
            throw new GuiliException(500, "连接失败");
        }

        if (code != null) {

            study1.setInfraredcode(code.replaceAll(" ", ""));

            studyService.save(study1);

            return R.ok().message("红外码获取成功！");
        }
        return R.error().message("红外码获取失败！");
    }

    /**
     * 查询学习到的红外码
     *
     * @return
     */
    @RequestMapping("search")
    public R search() {

        List<Study> studyList = studyService.list(new QueryWrapper<Study>().eq("status", 3).orderByDesc("id"));

        List list = new ArrayList();

        studyList.stream()
                .forEach(o -> {
                    StudyVo studyVo = new StudyVo();
                    studyVo.setInfraredcode(o.getInfraredcode());

                    studyVo.setInstructionid(o.getId());

                    studyVo.setInstructionname(o.getInstructionname());

                    list.add(studyVo);

                });
        return R.ok().data("items", list);
    }

    /**
     * 设置自学习状态
     *
     * @param study
     * @return
     * @throws IOException
     * @throws InterruptedException
     */
    @RequestMapping("setstatus")
    public R setstatus(@RequestBody Study study) throws IOException, InterruptedException {


        System.err.println(study);

        Study status = studyService.getOne(new QueryWrapper<Study>().eq("status", study.getStatus()).eq("ipadress", study.getIpadress()).eq("port", study.getPort()).eq("adresscode", study.getAdresscode()).eq("Infraredcode", "-1"));

        if (status == null) {
            Study study1 = new Study();

            BeanUtils.copyProperties(study, study1);
            System.out.println(study1.getIpadress());
            study1.setInstructioncode(study.getStatus().equals("1") ? study1.getAdresscode() + Code.getstartcode() : study1.getAdresscode() + Code.getendcode());
            System.out.println(study1.getInstructioncode());
            study1.setInstructionname(study.getStatus().equals("1") ? "开机" : "关机");

            System.err.println(study1);

            String code = studyService.setstatus(study1);

            if (code != null) {

                studyService.save(study1);

            }

            return R.ok().data("data", code);

        }

        String code = studyService.setstatus(status);
        return R.ok().data("data", code);

    }

    /**
     * 红外码验证
     *
     * @param map
     * @return
     */
    @RequestMapping("sendcheck")
    public R sendcheck(@RequestBody HashMap<String, String> map) {

        Study serviceById = studyService.getById(map.get("id"));

        String infraredcode = serviceById.getInfraredcode();

        System.out.println("serviceByID==================>" + serviceById);

        String newinfraredcode = "67" + "006E" + Integer.toHexString(infraredcode.length() / 2) + infraredcode;

        System.err.println(map.get("adcode"));

        boolean result = modBusCommand.infrared(map.get("ipaddress"), Integer.parseInt(map.get("port")), map.get("adcode"), newinfraredcode);

        return R.ok().data("data", result);
    }

    @PostMapping("del")
    public R del(@RequestBody HashMap<String, Integer> map) {

        boolean id = studyService.removeById(map.get("id"));

        if (id) {
            return R.ok();
        }

        return R.error();

    }

    /**
     * 指令打包分发
     *
     * @param list
     * @return
     */
    @RequestMapping("bagdown/{adcode}/{ipaddress}/{port}")
    public R bagdown(@RequestBody List<StudyVo> list, @PathVariable(name = "adcode") String adcode, @PathVariable(name = "ipaddress") String ipaddress, @PathVariable(name = "port") String port) {

        System.out.println(ipaddress + "]]]]]]]" + port);

        Study serviceById = studyService.getById(list.get(0).getInstructionid());

        final String[] code = {""};

        List newlist = new ArrayList();

        list.stream().forEach(o -> {

            Study one = studyService.getOne(new QueryWrapper<Study>().eq("id", o.getInstructionid()));

            code[0] = "67" + "006F" + one.getControllerid() + Integer.toHexString(o.getInfraredcode().length() / 2) + o.getInfraredcode();

            result = modBusCommand.infrared(ipaddress, Integer.parseInt(port), adcode, code[0]);
            //result=false;
            while (!result) {
                result = modBusCommand.infrared(ipaddress, Integer.parseInt(port), adcode, code[0]);
                //result=false;
                //System.out.println("result = " + result);
//                try {
//                    Thread.sleep(3000);
//                    result=true;
//                    System.out.println("result = " + result);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }

            newlist.add(result);

        });

        return R.ok().data("data", newlist);

    }

    /**
     * 查询指令模板封装vo交给前端解析（名称，控制号）
     *
     * @return
     */
    @RequestMapping("searchInname")
    public R searchInname() {


        List<Study> list = studyService.list(new QueryWrapper<Study>().eq("status", 3));

        List<InnameVo> newlist = new ArrayList();


        list.stream()
                .forEach(o -> {
                    InnameVo innameVo = new InnameVo();
                    innameVo.setValue(String.valueOf(o.getControllerid()));
                    innameVo.setLabel(o.getInstructionname());
                    newlist.add(innameVo);
                });

        return R.ok().data("list", newlist);


    }

    /**
     * 在线控制
     *
     * @param id 指令id，对应下位机指令控制号
     */
    @RequestMapping("online/{id}/{adcode}/{ipaddress}/{port}")
    public R online(@PathVariable String id, @PathVariable String adcode, @PathVariable String ipaddress, @PathVariable String port) throws IOException {

        Study serviceOne = studyService.getOne(new QueryWrapper<Study>().eq("controllerid", id));

        String Instructioncode = "06" + "0066" + serviceOne.getControllerid();

        serviceOne.setInstructioncode(Instructioncode);

        boolean infrared = modBusCommand.infrared(ipaddress, Integer.parseInt(port), adcode, serviceOne.getInstructioncode());

        return R.ok().data("data", infrared);

    }

    /**
     * 查询指令模板
     *
     * @return
     */
    @RequestMapping("searchinstructions")
    public R searchinstructions() {


        List<instruname> list = instrunameService.list();

        System.out.println("list = " + list);

        return R.ok().data("data", list);


    }


}
